# -*- coding: UTF-8 -*-
# @Time    : 2021/7/11 23:30
# @Author  : Sun
# @Email   : xxxxxxxxxxx@xxx.com
# @File    : mitm_rewrite.py
# @software: PyCharm
# 文件注释  :
import json

from mitmproxy import ctx, http

class MitmRewrite:

    def __init__(self):
        pass

    # 这里相当于方法的重写，函数名字是固定的
    def response(self, flow: http.HTTPFlow):
        if "stock.xueqiu.com/v5/stock/batch" in flow.request.pretty_url:
            # 文本格式打印返回值
            ctx.log.info("Rewrite name返回值" + flow.response.text)
            # 将json转换成字典格式
            # json -> dict -> json ->返回
            data = json.loads(flow.response.text)
            # 修改对应的值
            data["data"]["items"][0]["quote"]["name"] = '张三'
            # json.dumps将文本序列化传入response
            flow.response.text = json.dumps(data)


addons = [
    MitmRewrite()
]


if __name__ == '__main__':
    from mitmproxy.tools.main import mitmdump

    # 使用debug模式启动mitmdump
    # 返回中添加参数--ssl-insecure忽略证书认证报错
    mitmdump(['-p', '8080', '-s', __file__, '--ssl-insecure'])
